package com.example.pay.service;

import com.example.pay.entity.MemberOrder;
import com.example.pay.entity.MemberPackageItem;
import com.example.pay.entity.PointsConfigDetail;
import com.example.pay.mapper.MemberOrderMapper;
import com.example.pay.mapper.MemberPackageItemMapper;
import com.example.pay.mapper.PointsConfigDetailMapper;
import com.example.pay.util.OrderCodeGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class OrderService {
    private final MemberOrderMapper orderMapper;
    private final MemberPackageItemMapper itemMapper;
    private final PointsConfigDetailMapper pointsConfigDetailMapper;

    public MemberOrder createOrder(String productType, Long productId, Integer purchaseType,
                                   String userId, String userName, String userPhone) {
        BigDecimal amount = resolveAmount(productType, productId,purchaseType);

        MemberOrder order = new MemberOrder();
        order.setOrderCode(OrderCodeGenerator.generate(32));
        order.setProductType(productType);
        order.setProductId(productId);
        order.setPurchaseType(purchaseType);
        order.setPayAmount(amount);
        order.setPayStatus(0);
        order.setOrderStatus(0);
        order.setUserId(userId);
        order.setUserName(userName);
        order.setUserPhone(userPhone);
        order.setOrderTime(LocalDateTime.now());
        orderMapper.insert(order);
        return order;
    }

    private BigDecimal resolveAmount(String productType, Long productId,Integer purchaseType) {
        if ("10001".equals(productType)){
            PointsConfigDetail detail = pointsConfigDetailMapper.selectById(productId);
            if (detail == null) {
                throw new IllegalArgumentException("商品不存在: " + productId);
            }
            return new BigDecimal(detail.getPoints());
        }else {
            // 简化：若商品类型为会员套餐，取当前价
            MemberPackageItem item = itemMapper.selectById(productId);
            if (item == null) {
                throw new IllegalArgumentException("商品不存在: " + productId);
            }
            if (item.getState() != null && item.getState() == 0) {
                throw new IllegalStateException("商品已下架或无效: " + productId);
            }
            if (purchaseType == 3){
                return item.getCurrentPrice().multiply(BigDecimal.valueOf(10));
            }
            return item.getCurrentPrice();
        }
    }
}
